/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.http.HttpSession;
import progin.java.User;

/**
 *
 * @author Dawn
 */
@WebServlet(name="LoginProcess", urlPatterns={"/LoginProcess"})
public class LoginProcess extends HttpServlet {

    boolean executed = false;
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ResultSet rst=null;
        Statement stm=null;
        
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Login Processing</title>");
            //out.println("</head>");
            //out.println("<body>");
            //out.println("<h1>Servlet LoginProcess at " + request.getContextPath () + "</h1>");
            //out.println("</body>");
            //out.println("</html>");

            Connection connection = null;

            try{
                try {
                    Class.forName("com.mysql.jdbc.Driver").newInstance();
                } catch (InstantiationException ex) {
                    Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            catch (ClassNotFoundException ex){
            }

            String Username = request.getParameter("Login_Username");
            String Password = request.getParameter("Login_Password");

            connection = DriverManager.getConnection("jdbc:mysql://localhost/chatter?user=root&password=");

            stm=connection.createStatement();
            if (stm.execute("select * from users where Username ='" + Username + "' AND Password = '"+ Password +"'"))
            {
                rst=stm.getResultSet();
            }
            if (rst != null)
            {
                if (rst.next())
                {
                    if (!rst.getBoolean("Banned"))
                    {
                        if (rst.getString("Role").equals("Admin"))
                        {
                            out.println("<meta HTTP-EQUIV='REFRESH' content='3; url=admin.jsp'>");
                            HttpSession session = request.getSession();
                            User user = new User(Username, request.getRemoteAddr(), 0);
                            session.setAttribute("usr", user);
                            response.sendRedirect("Admin");
                        }
                        else
                        {
                            out.println("<meta HTTP-EQUIV='REFRESH' content='3; url=Chat.jsp'>");
                            HttpSession session = request.getSession();
                            int role = 0;
                            if (rst.getString("Role").equals("Moderate"))
                            {
                                User user = new User(Username, request.getRemoteAddr(), 1);
                                session.setAttribute("usr", user);
                                role = 2;
                            }
                            else
                            {
                                User user = new User(Username, request.getRemoteAddr(), 2);
                                session.setAttribute("usr", user);
                                role = 1;
                            }
                            session.setAttribute("Username", rst.getString("Username"));
                            stm.execute("INSERT INTO onlineuser VALUES ('"+ Username +"',now())");
                            response.sendRedirect("Chat.jsp?Username=" + Username + "&Role=" + role); //Main function, still figuring out the other functions
                        }
                    }
                    else
                    {
                        response.sendRedirect("index.jsp?s=8080");
                    }
                }
                else
                {
                    response.sendRedirect("index.jsp?s=1"); // Main function
                }
            }
            out.println("</body>");
            out.println("</html>");

            connection.close();

        } catch (SQLException ex) {
            Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            rst.close();
            stm.close();
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
